/**
 * PasswdFileParser.java 16.06.2006
 */
package org.dicr.sys.linux;

import java.io.*;
import java.util.*;
import java.util.logging.*;

import org.dicr.util.data.*;
import org.dicr.util.data.exc.*;

/**
 * Password file parser
 * 
 * @author <A href='http://dicr.org'>Igor A Tarasov</A>
 * @version 060616
 */
public class PasswdFileParser {

	private static final Logger log = Logger.getLogger(PasswdFileParser.class.getName());

	/**
	 * Parse password file.
	 * 
	 * @param in
	 *            input data reader
	 * @throws IOException
	 * @return password file elements map, key is the user name
	 */
	public static Map<String, SysUser> parse(Reader in) throws IOException {
		if (in == null) throw new IllegalArgumentException("null input");
		Map<String, SysUser> sysUsers = new HashMap<>();
		BufferedReader reader = new BufferedReader(in);
		while (true) {
			String line = reader.readLine();
			if (line == null) break;
			line = StringUtils.normalize(line);
			if (line == null || line.startsWith("#")) continue;
			String[] fields = line.split(":", 7);
			try {
				if (fields.length < 6) throw new FileFormatException(line);
				String name = fields[0];
				String passwd = ("x".equals(fields[1]) ? null : fields[1]);
				int uid = Integer.parseInt(fields[2]);
				int gid = Integer.parseInt(fields[3]);
				String fullName = StringUtils.normalize(fields[4]);
				String homeDir = fields[5];
				String shell = (fields.length > 6) ? fields[6] : null;
				sysUsers.put(name, new SysUser(name, passwd, uid, gid, fullName, homeDir, shell));
			} catch (Exception fex) {
				log.log(Level.WARNING, "error parsing password file line: " + line, fex);
			}
		}
		reader.close();
		return sysUsers;
	}
}
